<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, InfoFilled, PictureFilled, Document, Plus } from '@element-plus/icons-vue'
import axios from 'axios'

// 筛选表单
const filterForm = ref({
  name: '',
  categoryId: '',
  storeId: ''
})

// 表格数据
const tableData = ref([])

// 分页
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(1)

// 分类选项
const categories = ref([])
// 门店选项
const stores = ref([])

const dishStatus = ref([])

// 获取分类选项
const getCategories = () => {
  axios.get('/dishManage/categories').then(res => {
    categories.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }))
  })
}

// 获取门店选项
const getStores = () => {
  axios.get('/dishManage/stores').then(res => {
    stores.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }))
  })
}
const getDishStatus=()=>{
  axios.get('/dishManage/dishStatus').then(res => {
    dishStatus.value = res.data.obj
})
}
// 初始化数据
const initData = () => {
  axios.get(`/dish/${pageNum.value}/${pageSize.value}`).then(res => {
    tableData.value = res.data.obj.data
    total.value = res.data.obj.total
  })
}

// 页面加载时初始化数据和选项
onMounted(() => {
  initData()
  getCategories()
  getStores()
})

// 查询处理
const handleQuery = () => {
axios.post(`/dishManage/search/${pageNum.value}/${pageSize.value}`,filterForm.value).then(res => {
  tableData.value=res.data.obj.data;
  total.value=res.data.obj.total;

})
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  if (filterForm.name || filterForm.categoryId || filterForm.storeId) {
    handleQuery()
  } else {
    initData()
  }
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  if (filterForm.name || filterForm.categoryId || filterForm.storeId) {
    handleQuery()
  } else {
    initData()
  }
}

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 菜品详情弹窗控制
const detailVisible = ref(false)
const detailLoading = ref(false)
const currentDish = ref({
  id: null,
  name: '',
  price: '',
  categoryName: '',
  storeName: '',
  status: '',
  image: '',
  description: '',
  createTime: ''
})

// 查看详情
// 在 handleView 方法中，获取当前时间并格式化
const handleView = async (row) => {
  detailVisible.value = true;
  detailLoading.value = true;
  try {
    // 这里调用获取菜品详情的API
    const res = await axios.get(`/dishManage/${row.id}`);
    currentDish.value = res.data.obj;

    // 获取当前时间并格式化
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    // 将格式化后的时间赋值给 currentDish.createTime
    currentDish.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error('获取菜品详情失败:', error);
    ElMessage.error('获取菜品详情失败');
  } finally {
    detailLoading.value = false;
  }
};

// 编辑
const handleEdit = (row) => {
  axios.get(`/dishManage/${row.id}`).then(res => {
    formData.value = res.data.obj
    dialogTitle.value = '编辑菜品'
    dialogVisible.value = true
    // 加载分类和门店数据
    getCategories();
    getStores();
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该菜品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/dishManage/dish/${row.id}`).then(res => {
      if (res.data.code === 200) {
        initData()
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 新增菜品
const dialogVisible = ref(false)
const dialogTitle = ref('新增菜品')
const formData = ref({
  id: '',
  name: '',
  price:'',
  categoryId: '',
  storeId: '',
  status: '',
  image: ''
})

const formRef = ref()

const formRules = reactive({
  name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  storeId: [{ required: true, message: '请选择门店', trigger: 'change' }]
})

const handleAdd = () => {
  formData.value= {
    id: '',
    name: '',
    price: '',
    categoryId: '',
    storeId: '',
    status: '',
    image: ''
  }
  axios.get('/dishManage/categories').then(res => {
    categories.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }));
  });
  axios.get('/dishManage/stores').then(res => {
    stores.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }))
  });

  dialogTitle.value = '新增菜品'
  dialogVisible.value = true
}

// 上传图片相关
//const uploadUrl = '/api/upload' // 替换为你的上传接口地址

const handleImageUpload = (response) => {
  if (response.code === 200) {
    alert(response.obj.filePath)
    formData.value.image = response.obj.filePath
  } else {
    ElMessage.error('图片上传失败')
  }
}

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return (isJPG || isPNG) && isLt2M
}

// 确认提交
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (formData.value.id) {
        axios.post('/dishManage/editDish', formData.value).then(res => {
          if (res.data) {
            dialogVisible.value = false
            initData();
            ElMessage.success('修改成功')
          } else {
            ElMessage.error(res.data.msg || '修改失败')
          }
        })
      } else {
        axios.post('/dishManage/addDish', formData.value).then(res => {
          if (res.data) {
            dialogVisible.value = false
            initData()
            ElMessage.success('添加成功')
          } else {
            ElMessage.error(res.data.msg || '添加失败')
          }
        })
      }
    } else {
      ElMessage.warning('请填写完整信息')
      return false
    }
  })
}
</script>

<template>
  <div class="dish-management">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="菜品名称">
          <el-input v-model="filterForm.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="filterForm.categoryId" placeholder="请选择类别" clearable style="width: 200px">
            <el-option v-for="category in categories" :key="category.value" :label="category.label" :value="category.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="门店">
          <el-select v-model="filterForm.storeId" placeholder="请选择门店" clearable style="width: 200px">
            <el-option v-for="store in stores" :key="store.value" :label="store.label" :value="store.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据列表 -->
    <div class="table-section">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">新增菜品</el-button>
      </div>
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" align="center" />
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="price" label="价格" width="120" align="center">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120" align="center" />

        <el-table-column prop="image" label="图片" width="180" align="center">
          <template #default="{ row }">
            <el-image
                v-if="row.image"
                :src="`public/food_images/${row.image}`"
                style="width: 150px; height: 150px; border-radius: 4px;"
                fit="cover"
                :preview-src-list="[`public/food_images/${row.image}`]"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>

        <el-table-column prop="storeName" label="所属门店" width="150" />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status===1 ? "在售":"停售" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页  -->
    <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 15, 20, 25]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!-- 菜品详情弹窗 -->
  <el-dialog
      v-model="detailVisible"
      title="菜品详情"
      width="50%"
      top="5vh"
  >
    <el-skeleton :loading="detailLoading" animated>
      <div class="detail-container">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3><el-icon><InfoFilled /></el-icon> 基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="菜品ID">{{ currentDish.id }}</el-descriptions-item>
            <el-descriptions-item label="菜品名称">{{ currentDish.name }}</el-descriptions-item>
            <el-descriptions-item label="价格">¥{{ currentDish.price?.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="分类">{{ currentDish.categoryName || '无' }}</el-descriptions-item>
            <el-descriptions-item label="所属门店">{{ currentDish.storeName || '无' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="currentDish.status === 1 ? 'success' : 'danger'">
                {{ currentDish.status === 1 ? '在售' : '停售' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentDish.createTime }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 图片展示 -->
        <div class="detail-section">
          <h3><el-icon><PictureFilled /></el-icon> 菜品图片</h3>
          <div class="image-container">
            <el-image
                v-if="currentDish.image"
                :src="`/food_images/${currentDish.image}`"
                :preview-src-list="[`/food_images/${currentDish.image}`]"
                fit="cover"
                style="width: 300px; height: 300px;"
            />
            <el-empty v-else description="暂无图片" :image-size="80" />
          </div>
        </div>
        <!-- 描述信息 -->
        <div class="detail-section" v-if="currentDish.description">
          <h3><el-icon><Document /></el-icon> 菜品描述</h3>
          <div class="description-box">
            {{ currentDish.description }}
          </div>
        </div>
      </div>
    </el-skeleton>

    <template #footer>
      <el-button type="primary" @click="detailVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 新增/编辑菜品弹窗 -->
  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
    >
      <el-form-item label="菜品名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入菜品名称" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="formData.price" placeholder="请输入菜品价格"/>
      </el-form-item>
      <el-form-item label="分类" prop="categoryName">
        <el-select v-model="formData.categoryId" placeholder="请选择分类" style="width: 100%">
          <el-option v-for="category in categories" :key="category.value" :label="category.label" :value="category.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="门店" prop="storeName">
        <el-select v-model="formData.storeId" placeholder="请选择门店" style="width: 100%">
          <el-option v-for="store in stores" :key="store.value" :label="store.label" :value="store.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">在售</el-radio>
          <el-radio :label="0">停售</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上传图片" prop="image">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/api/upload"
            :show-file-list="false"
            :on-success="handleImageUpload"
            :before-upload="beforeImageUpload"
        >
          <img v-if="formData.image" :src="formData.value.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>
<style scoped>
.dish-management {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.table-section {
  flex: 1;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-container {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 15px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  color: #333;
  margin-bottom: 15px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.detail-section h3 .el-icon {
  margin-right: 8px;
}

.image-container {
  display: flex;
  justify-content: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin: 10px 0;
}

.description-box {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>